package com.jiang.books.service.jpa;

import com.google.common.collect.Lists;
import com.jiang.books.domain.*;
import com.jiang.books.repository.IUserGroupRepository;
import com.jiang.books.service.IUserGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Service
@Transactional
public class UserGroupSpDataService implements IUserGroupService {

    @Autowired
    IUserGroupRepository repository;

    @PersistenceContext
    public EntityManager em;

    @Override
    @Transactional(readOnly = true)
    public List<UserGroup> findAll() {
        //System.out.println("repository =" + repository+" , em = "+ em)  ;
        Iterable<UserGroup> ugs = repository.findAll();
        return Lists.newArrayList(ugs);
    }

    @Override
    @Transactional(readOnly = true)
    public UserGroup findById(Long id) {
        return repository.findOne(id);
    }

    @Override
    @Transactional(readOnly = false)
    public UserGroup save(UserGroup ugroup) {
        return repository.save(ugroup);
    }

    @Override
    @Transactional(readOnly = false)
    public void delete(UserGroup ugroup) {
        repository.delete(ugroup);
    }

    @Override
    @Transactional(readOnly = true)
    public List<UserGroup> findAllChilderenByNativeQuery(Long id) {
        return em.createNativeQuery(FIND_ALL_CHILDEREN_QUERY, "UserGroupResult").setParameter("id", id).getResultList();
    }

    @Override
    @Transactional(readOnly = true)
    public List<UserGroup> findByGroupName(String findByGroupName) {
        return repository.findByGroupName(findByGroupName);
    }

}